// pages/index/index.js
Page({

    /**
     * 页面的初始数据
     */
    data: {
        userInfo: {
            avatarUrl: "", //用户头像
            nickName: "", //用户昵称
        },
        showLeft1: false,
        totalgrade: 2,
        wrongSum: 54,
        canIUse: wx.canIUse('button.open-type.getUserInfo'),
        isHide: false,
        gradeList: [],

        subjectList: [],
        unionid: ""
    },
    //侧边导航栏
    toggleLeft1() {
        this.setData({
            showLeft1: !this.data.showLeft1
        });
    },
    //榜单
    toRank: function () {
        wx.navigateTo({
            url: '../rank/rank',
        });
    },
    //关于页
    toAbout: function () {
        wx.navigateTo({
            url: '../about/about',
        });
    },
    //设置页
    setting: function () {
        wx.navigateTo({
            url: '../setting/setting',
        });
    },
    //查询年级科目
    querySubject(e) {
        var that = this;
        var id = e.currentTarget.id;

        wx.navigateTo({
            url: "../subject/subject?grade=" + id + "&wrongNum=" + that.data.wrongSum + "&unionid=" + that.data.unionid,
        })
        // wx.request({
        //   url: 'http://localhost:8080/eb-back-web/subject',
        //   method: 'post',
        //   header: {
        //     'content-type': 'application/x-www-form-urlencoded'
        //   },
        //   data: { grade: id ,unionid:that.data.unionid},
        //   success: function (res) {
        //     //点击年级
        //     let grade = res.data.subject;
        //     //错题总数（传给下页显示）
        //     let wrongNum = that.data.wrongSum;

        //   },
        //   fail: function () {
        //     console.log('跳转科目页出错')
        //   }
        // })
    },
    /**
     * 生命周期函数--监听页面加载
     */
    headimageLoad: function (e) {
        var _this = this;
        var $width = e.detail.width,    //获取图片真实宽度
            $height = e.detail.height,
            ratio = $width / $height;   //图片的真实宽高比例
        if ($width > ($height*1.25)) {
            var viewHeight = 600;
            var viewWidth = 600 * ratio;
        } else {
            var viewWidth = 750;
            var viewHeight = 750 / ratio;
        }

        _this.setData({
            himgwidth: viewWidth,
            himgheight: viewHeight
        })
    },
    onLoad: function (options) {
        var that = this;
        // 查看是否授权
        wx.getSetting({
            success: function (res) {
                if (res.authSetting['scope.userInfo']) {
                    wx.getUserInfo({
                        success: function (res) {
                            console.log(res);
                            var avatarUrl = 'userInfo.avatarUrl';
                            var nickName = 'userInfo.nickName';
                            that.setData({
                                [avatarUrl]: res.userInfo.avatarUrl,
                                [nickName]: res.userInfo.nickName,
                            })

                        }
                    })
                } else {
                    // 用户没有授权
                    // 改变 isHide 的值，显示授权页面
                    that.setData({
                        isHide: true
                    });
                }
            }
        });
        wx.login({
            success: function (r) {
                var code = r.code;//登录凭证
                if (code) {
                    //2、调用获取用户信息接口
                    wx.getUserInfo({
                        success: function (res) {
                            console.log({encryptedData: res.encryptedData, iv: res.iv, code: code})
                            //3.解密用户信息 获取unionId
                            //3.请求自己的服务器，解密用户信息 获取unionId等加密信息
                            wx.request({
                                url: 'http://localhost:8080/eb-back-web/index',//自己的服务接口地址
                                method: 'post',
                                header: {
                                    'content-type': 'application/x-www-form-urlencoded'
                                },
                                data: {encryptedData: res.encryptedData, iv: res.iv, code: code},
                                success: function (data) {
                                   // var query_clone = JSON.parse(decodeURIComponent(JSON.stringify(data.data)));
                               //   console.log(query_clone);
                                    var app = getApp();     // 取得全局App
                                  app.globalData.uid = data.data.unionId ;
                                  app.globalData.backgroundUrl=data.data.backUrl;
                                  // 取得全局变量需要的值
                                    that.setData({
                                      gradeList: data.data.grade,
                                      backgroundUrl: data.data.backUrl,
                                      wrongSum: data.data.wrongNum,
                                      totalgrade: data.data.gradeNum,
                                        unionid: data.data.unionId

                                    });
                                },
                                fail: function () {
                                    console.log('系统错误')
                                }
                            })
                        },
                        fail: function () {
                            console.log('获取用户信息失败')
                        }
                    })
                } else {
                    console.log('获取用户登录态失败！' + r.errMsg)
                }
            },
            fail: function () {
                callback(false)
            }
        });
    },

    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady: function () {
        // 使用 wx.createContext 获取绘图上下文 context
        var ctx = wx.createCanvasContext('canvas1')
        ctx.arc(41, 125, 25, 0, 2 * Math.PI)
        ctx.setFillStyle('white')
        ctx.fill()

        ctx.beginPath()
        ctx.rect(0, 100, 41, 50)

        ctx.fill()

        ctx.beginPath()
        ctx.arc(41, 125, 20, 0, Math.PI * 2)
        ctx.setFillStyle('#f4f6f9')
        ctx.fill()
        ctx.draw()

    },
    test: function () {
        this.setData({
            showLeft1: !this.data.showLeft1
        });
    },
    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide: function () {

    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload: function () {

    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh: function () {

    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom: function () {

    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage: function () {

    },
    bindGetUserInfo: function (e) {
        if (e.detail.userInfo) {
            //允许
            var that = this;
            console.log("用户的信息如下：");
            console.log(e.detail.userInfo);
            //授权成功后,通过改变 isHide 的值，让实现页面显示出来，把授权页面隐藏起来
            that.setData({
                isHide: false,
            });
            wx.getUserInfo({
                success: function (res) {
                    console.log(res);
                    var avatarUrl = 'userInfo.avatarUrl';
                    var nickName = 'userInfo.nickName';
                    that.setData({
                        [avatarUrl]: e.detail.userInfo.avatarUrl,
                        [nickName]: e.detail.userInfo.nickName,
                    })
                }
            })
        } else {
            //拒绝
            wx.showModal({
                title: '警告',
                content: '请允许授权用户信息，获得更好的服务',
                showCancel: false,
                confirmText: '返回授权',
                success: function (res) {
                    // 用户没有授权成功，不需要改变 isHide 的值
                    if (res.confirm) {
                        console.log('用户点击了“返回授权”');
                    }
                }
            });
        }
    },


    onShow:function(){
        this.setData({
            backgroundUrl: getApp().globalData.backgroundUrl
        })
    }
})
